package com.ruoyi.web.controller.contest;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.contest.domain.Teacher;
import com.ruoyi.contest.service.ITeacherService;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 教师信息Controller
 *
 * @author ruoyi
 * @date 2023-02-16
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/contest/teacher")
public class TeacherController extends BaseController
{
    private final ITeacherService teacherService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询教师信息列表
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:list')")
    @GetMapping("/list")
    public TableDataInfo list(Teacher teacher)
    {
        startPage();
        List<Teacher> list = teacherService.selectTeacherList(teacher);
        for (Teacher t : list) {
            SysDept sysDept = deptService.selectDeptById(t.getDeptId());
            t.setDeptName(sysDept.getDeptName());
            SysUser user = userService.selectUserById(t.getUserId());
            String phonenumber = user.getPhonenumber();
            t.setPhone(phonenumber);
        }
        return getDataTable(list);
    }

    /**
     * 导出教师信息列表
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:export')")
    @Log(title = "教师信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Teacher teacher)
    {
        List<Teacher> list = teacherService.selectTeacherList(teacher);
        ExcelUtil<Teacher> util = new ExcelUtil<Teacher>(Teacher.class);
        util.exportExcel(response, list, "教师信息数据");
    }

    /**
     * 获取教师信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:query')")
    @GetMapping(value = "/{teacherId}")
    public AjaxResult getInfo(@PathVariable("teacherId") Long teacherId)
    {
        return success(teacherService.getById(teacherId));
    }

    /**
     * 新增教师信息
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:add')")
    // @Log(title = "教师信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,String> m) {
        System.out.println(m);
        SysUser user = new SysUser();
        // 必要信息
        user.setUserName(m.get("userName"));
        user.setNickName(m.get("nickName"));
        user.setPassword("123456");
        user.setSex(m.get("sex"));
        user.setEmail(m.get("email"));
        user.setStatus("1");
        user.setPhonenumber(m.get("phonenumber"));
        long postId = Long.parseLong(m.get("post"));
        user.setPostIds(new Long[]{postId});

        // {userName=dome1, nickName=卢俊, sex=0, email=1295074635@qq.com, professional=0, post=1, phonenumber=17585367620, status=1, deptId=210, research=人工智能, brief=<p>人工智能简介</p>, remark=备注}

        // user.setDeptId();
        // user.setPostIds();

        // 数据校验
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return error("新增用户'" + user.getUserName() + "'失败，教师工号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增教师'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增教师'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        int i = userService.insertUser(user);

        SysUser sysUser = userService.selectUserByUserName(user.getUserName());

        // 判断用户是否添加成功
        Teacher teacher = null;
        if (i > 0) {
            // 添加教师
            teacher = new Teacher();
            teacher.setUserId(sysUser.getUserId());
            teacher.setName(sysUser.getNickName());
            teacher.setGender(sysUser.getSex());
            teacher.setProfessional(m.get("professional"));
            teacher.setPost(m.get("post"));
            Long deptId = Long.valueOf(m.get("deptId"));
            teacher.setDeptId(deptId);
            teacher.setResearch(m.get("research"));
            teacher.setBrief(m.get("brief"));
            teacher.setRemark(m.get("remark"));
            // 职称 职务 部门 手机 研究方向 简介 备注
        }
        return toAjax(teacherService.insertTeacher(teacher));
    }

    /**
     * 修改教师信息
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:edit')")
    @Log(title = "教师信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Teacher teacher)
    {
        return toAjax(teacherService.updateById(teacher));
    }

    /**
     * 删除教师信息
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:remove')")
    @Log(title = "教师信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{teacherIds}")
    public AjaxResult remove(@PathVariable Long[] teacherIds)
    {

        return toAjax(teacherService.removeByIds(Arrays.asList(teacherIds)));
    }

    /**
     * 查询教师信息列表
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:list')")
    @GetMapping("/listWithDeptName")
    public TableDataInfo listWithDeptName(Teacher teacher)
    {
        startPage();
        List<Teacher> list = teacherService.listWithDeptName(teacher);
        for (Teacher t : list) {
            SysDept sysDept = deptService.selectDeptById(t.getDeptId());
            SysUser user = userService.selectUserById(t.getUserId());
            String phonenumber = user.getPhonenumber();
            t.setPhone(phonenumber);
            t.setDeptName(sysDept.getDeptName());
        }

        return getDataTable(list);
    }

    /**
     * 获取教师信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('contest:teacher:query')")
    @GetMapping(value = "/detailWithDeptName/{teacherId}")
    public AjaxResult detailWithDeptName(@PathVariable("teacherId") Long teacherId)
    {
        return success(teacherService.detailWithDeptName(teacherId));
    }
}
